package com.carryking.smart.rpc.utils;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoFactory;
import com.esotericsoftware.kryo.pool.KryoPool;

import java.io.ByteArrayOutputStream;

/**
 * 序列化工具类
 * Created by jincarry on 2018/1/10.
 */
public class KryoUtils {

    private static final KryoFactory factory = new KryoFactory() {
        public Kryo create () {
            Kryo kryo = new Kryo();
            return kryo;
        }
    };

    private static final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();

    private static Kryo getKryo() {
        return pool.borrow();
    }

    public static byte[] wirte(Object object) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Output output = new Output(byteArrayOutputStream);
        getKryo().writeObject(output, object);
        return output.getBuffer();
    }

    public static <T> T read(byte[] bytes, Class clasz) {
        Input input = new Input(bytes);
        return (T) getKryo().readObject(input, clasz);
    }
}
